import { useLazyQuery, useQuery } from "@apollo/client";
import {
  getProductInfo_service,
  getProductsByType_service,
  getRecommendProducts_service,
} from "../../graphql/product";
import { ProductType } from "../../types/product";
import { PageType } from "../../constant";

export const useFetch_getProductsByType = () => {
  const [fun, { loading }] = useLazyQuery(getProductsByType_service, {
    fetchPolicy: "network-only",
  });

  const getProductsByType = async (
    page: {
      pageNum: number;
      pageSize: number;
    },
    type?: string,
    name?: string
  ) => {
    const res = (await fun({
      variables: {
        page,
        type: type === "all" ? undefined : type,
        name,
      },
    })) as {
      data: {
        getProductsByType: {
          message: string;
          page: PageType;
          data: ProductType[];
        };
      };
    };
    return res?.data?.getProductsByType;
  };
  return { getProductsByType, getProductsByTypeLoading: loading };
};

export const useFetch_getRecommendProducts = (orgId: string) => {
  const { data, loading } = useQuery(getRecommendProducts_service, {
    variables: {
      orgId,
    },
    fetchPolicy: "network-only",
  });
  return { data: data?.getRecommendProducts.data as ProductType[], loading };
};

export const useFetch_getProductInfo = (id: string) => {
  const { data, loading, refetch } = useQuery(getProductInfo_service, {
    variables: {
      id,
    },
    fetchPolicy: "network-only",
  });
  return {
    data: data?.getProductInfo.data as ProductType,
    loading,
    refetch,
  };
};
